import React, { useEffect, Suspense, useState } from 'react';
import { Layout, Menu, ConfigProvider, Spin, Breadcrumb } from 'antd';
import { Outlet, useNavigate, useLocation, Link } from 'react-router-dom';
import './index.less';

const { Sider, Content } = Layout;

// 数据源导航配置
const dsNavigation = [
  {
    key: '/datasource/vector',
    label: (<Link to="vector">矢量数据</Link>)
  },
  {
    key: '/datasource/grid',
    label: (<Link to="grid">栅格数据</Link>)
  },
  {
    key: '/datasource/three',
    label: (<Link to="three">三维数据</Link>)
  },
  {
    key: '/datasource/tile',
    label: (<Link to="tile">瓦片数据</Link>)
  }
];

// 自定义主题配置
const themeConfig = {
  components: {
    Menu: {
      itemHeight: 56 // 菜单项高度
    }
  }
};

// 默认的面包屑导航
const defaultCrumb = [{ title: '数据源' }];

export default function Datasource() {
  const navigate = useNavigate();
  const location = useLocation();
  const [crumbList, setCrumbList] = useState(defaultCrumb);

  // 组件挂载时跳转到矢量数据页面
  useEffect(() => {
    navigate('vector');
    // 空依赖数组确保只调用一次
  }, []);

  // 监听路由变化，更新面包屑导航
  useEffect(() => {
    const paths = location.pathname.split('/');
    const pageTitle = paths[paths.length - 1];
    switch (pageTitle) {
      case 'vector':
        setCrumbList([...defaultCrumb, { title: '矢量数据' }]);
        break;
      case 'grid':
        setCrumbList([...defaultCrumb, { title: '栅格数据' }]);
        break;
      case 'three':
        setCrumbList([...defaultCrumb, { title: '三维数据' }]);
        break;
      case 'tile':
        setCrumbList([...defaultCrumb, { title: '瓦片数据' }]);
        break;
      default:
        setCrumbList(defaultCrumb);
    }
  }, [location]);

  return (
    <ConfigProvider theme={themeConfig}>
      <Layout className='layout-style'>
        {/* 侧边栏 */}
        <Sider theme='light' width='300' className='sider-style'>
          <Menu mode="inline" items={dsNavigation} selectedKeys={[location.pathname]} />
        </Sider>
        {/* 内容区域 */}
        <Content className='my-content'>
          <div className='datasource-list'>
            {/* 面包屑导航 */}
            <Breadcrumb style={{ margin: '16px 0' }} items={crumbList}></Breadcrumb>
            {/* 懒加载路由组件 */}
            <Suspense fallback={<Spin />}>
              <div className="datasource-outlet">
                <Outlet />
              </div>
            </Suspense>
          </div>
        </Content>
      </Layout>
    </ConfigProvider>
  );
}
